package com.star.spring.deferred.service.thread.basic;


import com.star.spring.deferred.utils.CommonUtils;

import java.util.concurrent.TimeUnit;

/**
 * @description: join应用
 * @author: star
 * @create: 2024-12-29 22:20
 **/

public class JoinDemo {

    static int result = 0;
    static int result1 = 0;
    static int result2 = 0;


    public static void main(String[] args) throws InterruptedException {
//        test1();
//        testJoin();
        testJoin2();
        System.out.println(result);
    }

    /**
     * 主线程sleep等待线程执行返回的结果
     * @throws InterruptedException
     */
    static void test1() throws InterruptedException {
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                result = 1;
            }
        });
        t1.start();
        TimeUnit.SECONDS.sleep(1);

    }


    /**
     * join方法，等待线程执行完毕，主线程去拿结果
     */
    static void testJoin() throws InterruptedException {
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                result = 1;
            }
        });
        t1.start();
        // 使用join
        t1.join();

    }

    /**
     * 等待两个想成的join方法的结果，查看耗时
     * @throws InterruptedException
     */
    static void testJoin2() throws InterruptedException {
        long start = System.currentTimeMillis();
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {

                CommonUtils.sleep(1);
                result1 = 1;

            }
        });

        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {

                CommonUtils.sleep(2);

                result2 = 2;
            }
        });
        t1.start();
        t2.start();

        t2.join();
        t1.join();
        // 计算时间间隔
        long end = System.currentTimeMillis();
        System.out.println(end - start);

    }

}
